package com.hyg.base.utils;

import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
import com.liulishuo.okdownload.core.listener.DownloadListener2;

import java.util.concurrent.atomic.AtomicLong;

public class StickersListener extends DownloadListener2 {

    private final StickersProgress listener;
    private long totalLength = 0;
    private final AtomicLong progress = new AtomicLong();

    public StickersListener(StickersProgress listener) {
        this.listener = listener;
    }

    @Override
    public void taskStart(@NonNull DownloadTask task) {
        progress.set(0);
    }


    @Override
    public void downloadFromBeginning(@NonNull DownloadTask task, @NonNull BreakpointInfo info, @NonNull ResumeFailedCause cause) {
        totalLength = info.getTotalLength();
    }


    @Override
    public void fetchProgress(@NonNull DownloadTask task, int blockIndex, long increaseBytes) {
        super.fetchProgress(task, blockIndex, increaseBytes);
        progress.addAndGet(increaseBytes);
        if(listener != null)
            listener.onProgress((int) (progress.get() * 1.0f / totalLength * 100));
    }


    @Override
    public void downloadFromBreakpoint(@NonNull DownloadTask task, @NonNull BreakpointInfo info) {
        super.downloadFromBreakpoint(task, info);
        totalLength = info.getTotalLength();
        progress.set(info.getTotalOffset());
    }

    @Override
    public void fetchEnd(@NonNull DownloadTask task, int blockIndex, long contentLength) {
        super.fetchEnd(task, blockIndex, contentLength);

    }

    @Override
    public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) {
        if (cause == EndCause.COMPLETED) {
            if (task.getFile() != null) {
                if(listener != null)
                    listener.onSuccess(task.getUri(), task.getFile().getPath(), task.getFile().getParent());
            }
        } else {
            if(listener != null)
                listener.onFail();
        }
    }

    public interface StickersProgress {

        void onProgress(int progress);

        void onFail();

        void onSuccess(Uri uri, String path, String name);

    }

}
